package com.learn.configuration;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Configuration
public class WebInterceptorsConfiguration implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册请求拦截器
        registry.addInterceptor(new HandlerInterceptor() {
                    /**
                     * 对拦截请求进行预处理：可对请求头进行设置、对token进行校验
                     * ·    决定handler和afterCompletion执不执行
                     *
                     * @param request
                     * @param response
                     * @param handler  Controller方法处理器
                     * @return 返回true则放行，返回false则不放行
                     * @throws Exception
                     */
                    @Override
                    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                        System.out.println("preHandle");
                        return true;
                    }
                    
                    /**
                     * 对拦截请求进行后处理：可对模型数据和视图进行修改
                     * ·    执不执行取决于handler执不执行，所以取决于preHandle放不放行
                     *
                     * @param request
                     * @param response
                     * @param handler      Controller方法处理器
                     * @param modelAndView 模型视图对象
                     * @throws Exception
                     */
                    @Override
                    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
                        System.out.println("postHandle");
                    }
                    
                    /**
                     * 视图渲染完成后的最终处理（整个流程完成后）：可对异常进行处理
                     * ·    执不执行取决于preHandle放不放行
                     *
                     * @param request
                     * @param response
                     * @param handler  Controller方法处理器
                     * @param ex       异常对象
                     * @throws Exception
                     */
                    @Override
                    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
                        System.out.println("afterCompletion");
                    }
                })
                // 拦截器生效路径
                .addPathPatterns("/**")
                // 拦截器不生效路径
                .excludePathPatterns("/hello/**");
    }
}
